package com.liz.restfulApi.nettyDubbo.controller;

import com.alibaba.fastjson.JSONObject;
import com.liz.restfulApi.nettyDubbo.domain.User;
import com.liz.restfulApi.nettyDubbo.annotation.*;
import com.liz.restfulApi.nettyDubbo.factory.UserThreadLocalFactory;
import com.liz.restfulApi.nettyDubbo.rest.HttpStatus;
import com.liz.restfulApi.nettyDubbo.rest.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.UUID;

//默认为单例，singleton = false表示启用多例。
//@RestController(singleton = false)
@RestController
@RequestMapping("/users")
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("")
    @JsonResponse
    public ResponseEntity<User> listUser() {
        User user = UserThreadLocalFactory.getUser();
        // 查询用户
        int id = new Random().nextInt(100);
        user.setId(id);
        user.setName("Test_name_" + id);
        user.setAge((short)new Random().nextInt());
        user.setUuid(UUID.randomUUID().toString());
        return ResponseEntity.ok().build(user);
    }



    @PutMapping("/{id}")
    public ResponseEntity<?> putMethod(@PathVariable("id") int id, @RequestBody String body) {
        // 更新用户
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMethod(@PathVariable int id) {
        // 删除用户
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping("")
    public ResponseEntity<?> postMethod(@RequestBody String body) {
        // 添加用户
        JSONObject json = JSONObject.parseObject(body);
        User user = new User();
        user.setId(json.getIntValue("id"));
        user.setName(json.getString("name"));
        user.setAge(json.getShortValue("age"));
        return ResponseEntity.status(HttpStatus.CREATED).build(user);
    }

}
